<?
require_once($r."_config/db.php");
require_once($r."_engine/types.php");
require_once($r."_engine/mail_functions.php");
require_once($r."_engine/c_sql_table.php");


$g_st_monitor = new CSqlTable("monitors", "id");
$g_st_monitor->field_types["created"]		    = "dt";
$g_st_monitor->field_types["last_update"]	    = "dt";
$g_st_monitor->field_types["rs_download_dt"]    = "dt";

$g_monitor_title_default = "Untitled";


class CMonitor
{
	var $id, $data;
	
	function CreateNew(&$account, $values, $quick_reg=false)
	{
		$this->InitNew($account);
		$this->LoadFromArray($values);
		
		global $g_st_monitor;
		$g_st_monitor->Insert($this->data);
		$this->id = mysql_insert_id();
		
		if ($quick_reg)
		{
			global $g_monitor_title_default;
			if ($this->data["title"] != $g_monitor_title_default)
				$name = $this->data["title"];
			else
				$name = $this->data["url"];
				
			/* Clear "approved" bit in status word */
			$this->data["status"] &= ~ MONITOR_STATUS_IS_APPROVED_MASK;
			
			$mail_message = 
				"Hello, \n".
				"\n".
				"Monitor Activation letter. To enable monitor (ack quick add) please click on the link below.\n".
				"\n".
				"Activation link: ".$this->GetActivationURL()."\n".
				"\n".
				"Regards\n".
				"With best regards W3Monitor\n".
				"http://www.w3monitor.com/\n";

			$data = array(
				"email_from" => "support@w3monitor.com",
				"email_to" => $account->data["email"],
				"email_subject" => "W3Monitor - monitor activation - ".$name,
				"email_template" => $mail_message,
			);
			//vd($data);
			
			global $g_spg;
			$g_spg->SendEmail($data);
		}
	}
	
	function InitNew(&$account)
	{
		$this->data = array();

		// Initialize monitor info
		$this->data["account_id"]		= $account->id;
		$this->data["created"]			= gmt_time();
		$this->data["activation_code"]	= md5(uniqid(rand()));
		$this->data["last_update"]		= mktime(0,0,0,1,1,2001);

		global $g_monitor_title_default;
		$this->data["title"]			= $g_monitor_title_default;
		$this->data["status"]		    = MONITOR_STATUS_IS_ACTIVE_MASK | 
										  MONITOR_STATUS_IS_APPROVED_MASK;
		$this->data["domain_name"] 		= "";
										  
		
		$categories = new CCategories($account);
		$this->data["category_id"]		= $categories->default_category_id;
		
		$this->data["frequency"]		= $account->data["def_frequency"];
		// monitor_at_time => current time (minuts should be: 0, 15, 30, 45)
		$this->data["monitor_at_time"]	= date("H") * 60 * 60 + round(date("i") / 15) * 15 * 60;

		$this->data["disable_top_list_stats"] = $account->data["def_disable_top_list_stats"];
		
		$this->data["xpath"] 			= "";
		$this->data["trigger_type"]		= TRIGGER_ANY_CHANGES;
		$this->data["alert_at_time"]	= -1;
		$this->data["alert_type"]		= $account->data["def_alert_type"];
		$this->data["alert_emails"]		= $account->data["def_alert_emails"];
		
		$this->data["enable_history"]	= 1;
		$this->data["highlight_font_color"]		= $account->data["def_highlight_font_color"];
		$this->data["highlight_bk_color"]		= $account->data["def_highlight_bk_color"];
		$this->data["highlight_font_style"]		= $account->data["def_highlight_font_style"];
		$this->data["proxy_port"]		= 0;

		$this->data["trigger_params"]	= "";
		$this->data["reference_url"]	= "";
		$this->data["http_user_agent_custom"]	= "";
		$this->data["http_cookies"]		= "";
		$this->data["trigger_params"]	= "";
		$this->data["http_form_content"]= "";
		$this->data["proxy_addr"]		= "";
	}

	function InitNewFromAnother(&$monitor_ref)
	{
		$a = array(
			/*"url",*/ "status", /*"title",*/ "category_id", "frequency", "monitor_at_time",
			"disable_top_list_stats", "trigger_params", "trigger_type", "alert_emails",
			"alert_freq", "alert_at_time", "alert_type", "reference_url", "enable_history",
			"highlight_font_color", "highlight_bk_color", "highlight_font_style",
			"http_user_agent_type", "http_user_agent_custom",
			"http_auth_user", "http_auth_password", "http_cookies", "http_form_content",
			"proxy_addr", "proxy_port", "proxy_auth_user", "proxy_auth_password"
		);
		
		//$this->data = array();

		// Copy monitor info
		foreach ($a as $f) $this->data[$f] = $monitor_ref->data[$f];
	}

	function GetActivationURL()
	{
		global $g_site_root;
		$url = "http://".$g_site_root."/members/monitor_activation_process.php?".
			"id=".$this->id."&activation_code=".$this->data["activation_code"];
		return $url;
	}

	function Activate($activation_code)
	{
		if ($activation_code != $this->data["activation_code"]) {
			 die("Incorrect data.");
		}
		
		/*
		TODO[KVV]: implement

		if ($this->data["activated"]) return;

		$this->Update(array("activated" => 1));
		*/
	}

	function LoadById($id)
	{
		return $this->LoadByQuery(
			"SELECT * FROM monitors WHERE id='$id';"
		);
	}
	function LoadByQuery($query)
	{
		global $g_st_monitor;
		$row = $g_st_monitor->SelectRow($query);
		if (!$row) return false;
		$this->LoadFromArray($row);
		return true;
	}
	
	function LoadFromArray($row)
	{
		foreach($row as $f => $v)
		{
			if (is_int($f)) continue;
			
			if ($f == "id")
				$this->id = $v;
			else
				$this->data[$f] = $v;
		}
	}
	
	function Update($values)
	{
		global $g_st_monitor;
		$this->LoadFromArray($values);
		return $g_st_monitor->Update($values, $this->id);
	}
	
	function CheckIfExist()
	{
		// Check if monitor with such URL already exists
		$q = '
SELECT * FROM monitors
WHERE account_id='.$this->data["account_id"].'
	AND id <> '.$this->id.'
	AND url = \''.normalize_url($this->data["url"]).'\';
';

		global $g_st_monitor;
		return ($g_st_monitor->SelectRow($q)) ? true : false;
	}
}



/* ----------------------------------------------------- */
/* -----             RELATED FUNCTIONS             ----- */
/* ----------------------------------------------------- */

function GetTop10Monitors()
{
/*  TOP 10 - old version from old site (front page)
	$res = execute_query('
	SELECT
		COUNT(*) AS cnt, url
	FROM monitors
	WHERE
		disable_top_list_stats <> 1
	GROUP BY url
	ORDER BY cnt DESC, id ASC
	LIMIT 0, 10;
	');
	
	$i = 0;
	while ($row = @mysql_fetch_array($res))
	{
		if ($i != 0) echo " &bull; ";
		
		echo '<a href="'.normalize_url($row["url"]).'" target="_blank">'.domain_name_from_url($row["url"]).'</a>'."\n";
		$i++;
	}
*/

/* TOP 10 - new site version (front page)
	$res = execute_query('
	SELECT
		COUNT(*) AS cnt,
	    MAX(last_update) AS max_last_update,
	    url
	FROM monitors
	WHERE
		disable_top_list_stats <> 1
	GROUP BY 
	    url
	ORDER BY 
	    cnt DESC, 
	    last_update DESC
	LIMIT 
	    0, 10;
	');
	
	$list = array();
	$i = 0;
	while ($row = @mysql_fetch_array($res))
	{
	    if ($i++ > 4) $i = 1;
	    
	    $time = delta_time_to_str(gmt_time() - strtotime($row["max_last_update"]), $g_delta_format_FP);
	    
	    $list[] = array(
	        'CNT'       => $row['cnt'],
	        'HREF'      => normalize_url($row["url"]),
	        'DOMAIN'    => domain_name_from_url($row["url"]),
	        'TIME'      => $time,
	    );
	}
	
	
	// Sort list by DOMAIN alphabetically
	function sort_top10_cmp($a, $b)
	{
	    return strcmp($a['DOMAIN'], $b['DOMAIN']);
	}
	usort ($list, "sort_top10_cmp");
	
	
	// Convert CNT to SIZE
	$list_cnt = array();
	foreach ($list as $k => $data)
	{
	    $list_cnt[$k] = (int)$data['CNT'];
	}
	
	arsort($list_cnt, SORT_NUMERIC);
	
	$i = 5; $prev_c = -1;
	foreach ($list_cnt as $k => $c)
	{
	    //echo $prev_c." ";
	    if ($i > 1 && $prev_c != $list[$k]['CNT'])
	    {
	        if ($prev_c > 0) $i--;
	        $prev_c = $list[$k]['CNT'];
	    }
	    $list[$k]['SIZE'] = $i;
	}
	//var_dump($list_cnt);
*/

	$res = execute_query('
	SELECT
		COUNT(*) AS cnt,
	    MAX(last_update) AS max_last_update,
	    domain_name
	FROM monitors
	WHERE
		disable_top_list_stats <> 1 AND
		domain_name <> ""
	GROUP BY 
	    domain_name
	ORDER BY 
	    cnt DESC, 
	    last_update DESC
	LIMIT 
	    0, 10;
	');
	
	global $g_delta_format_FP;
	
	$list = array();
	$i = 0;
	while ($row = @mysql_fetch_array($res))
	{
	    if ($i++ > 4) $i = 1;
	    
	    $time = delta_time_to_str(gmt_time() - strtotime($row["max_last_update"]), $g_delta_format_FP);
	    
	    $list[] = array(
	        'CNT'       => $row['cnt'],
	        'HREF'      => normalize_url($row["domain_name"]),
	        'DOMAIN'    => domain_name_from_url($row["domain_name"]),
	        'TIME'      => $time,
	    );
	}
	
	
	// Sort list by DOMAIN alphabetically
	function sort_top10_cmp($a, $b)
	{
	    return strcmp($a['DOMAIN'], $b['DOMAIN']);
	}
	usort ($list, "sort_top10_cmp");
	
	
	// Convert CNT to SIZE
	$list_cnt = array();
	foreach ($list as $k => $data)
	{
	    $list_cnt[$k] = (int)$data['CNT'];
	}
	
	arsort($list_cnt, SORT_NUMERIC);
	
	$i = 5; $prev_c = -1;
	foreach ($list_cnt as $k => $c)
	{
	    //echo $prev_c." ";
	    if ($i > 1 && $prev_c != $list[$k]['CNT'])
	    {
	        if ($prev_c > 0) $i--;
	        $prev_c = $list[$k]['CNT'];
	    }
	    $list[$k]['SIZE'] = $i;
	}
	//var_dump($list_cnt);
	
	return $list;
}
?>